package com.marco.gisdata.service.impl;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.marco.commons.SpringContextUtils;
import com.marco.gisdata.runnable.BaiduGisApiRunnable;
import com.marco.gisdata.service.AbstractGisService;
import com.marco.ipdata.runnable.BaiduApiRunnable;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;

/**
 * BaiduGisServiceImpl.java
 * Create on 2017/5/5
 * Copyright(c) JD Inc 2017. All Rights Reserved.
 * <pre>
 * 功能说明：
 * </pre>
 */
@Transactional
@Service
public class BaiduGisServiceImpl extends AbstractGisService {
    private static final Logger logger = LoggerFactory.getLogger(BaiduGisServiceImpl.class);
    private static final ObjectMapper jsonParaser = new ObjectMapper();
    private static final JavaType javaType = jsonParaser.getTypeFactory().constructMapType(Map.class, String.class, String.class);
    private static final String URL = "http://api.map.baidu.com/geocoder/v2/";
    private static List<String> AKS;
    @Autowired
    private ThreadPoolTaskExecutor executor;
    // 公用线程池配置
    @Value("${executor.queue.capacity}")
    private Integer executorQueueCapacity;
    @PostConstruct
    public void AKSETS() {
        AKS = Lists.newArrayList();
        AKS.add("ayr3xBt0tB7iezSs6ibiMyWo");
//        AKS.add("dOYd4yZZOWD7yjKc9bhGZuEc");
//        AKS.add("IYq0mZGy3ATu9O2RIGvSmqcG");
//        AKS.add("yj5kXONt3RgxCNOu2bE76W2O");
    }

    @Override
    public void obtainApiDataByParam() {
        for (int i = 0; i < AKS.size(); i++) {
            String ak = AKS.get(i);
            BaiduGisApiRunnable runnable = (BaiduGisApiRunnable) SpringContextUtils.getBeanById("baiduGisApiRunnable");
            runnable.setAk(ak);
            runnable.setThreadName("百度线程" + i);
            while (executor.getThreadPoolExecutor().getQueue().size() >= executorQueueCapacity) {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    logger.error("发送消息任务信息:线程等待出现异常", e);
                }
            }
            executor.execute(runnable);
        }
    }

    @Override
    protected String resolveResult(String result) {
        try {
            //对百度返回的结果进行解析，并进行封装
            if (StringUtils.isBlank(result)) {
                return null;
            }
            Map resultMap = jsonParaser.readValue(result, Map.class);
            //状态为0表示返回正常 百度接口无国外数据
            if (resultMap.get("status") != null && resultMap.get("status").toString().equals("0")) {
                Map tmp = (Map) resultMap.get("result");
                Map rs =(Map)tmp.get("addressComponent");
                StringBuilder sb = new StringBuilder();
                if (rs.get("country").toString().equals("中国")) {
                    sb.append(rs.get("province").toString());
                    sb.append(rs.get("city").toString());
                    sb.append(rs.get("district").toString());
                }
                return sb.toString();
            }
        } catch (Exception e) {
            logger.error("解析API 返回结果出现异常", e);
        }
        return null;
    }

    @Override
    protected Logger getLogger() {
        return logger;
    }

    @Override
    protected String url() {
        return URL;
    }
}
